<template>
  <el-upload
    class="text-center"
    :class="{ 'avatar-uploader': isPreview }"
    :http-request="fileUploade"
    :show-file-list="false"
    accept="image/*"
  >
    <slot>
      <el-button type="primary" :loading="loading">{{ text }}</el-button>
    </slot>
  </el-upload>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { uploadApi } from "@/api/common.api";
export default defineComponent({
  props: {
    text: {
      type: String,
      default: "点击上传图片",
    },
    isPreview: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    let loading = ref(false);
    let fileInput: HTMLInputElement | null = null;

    const triggerUpload = () => {
      if (!fileInput) {
        fileInput = document.querySelector(".el-upload__input") as HTMLInputElement;
      }
      fileInput.click();
    };

    let fileUploade = async (file: any) => {
      loading.value = true;
      let formData = new FormData();
      formData.append("file", file.file);
      try {
        let res: any = await uploadApi(formData);
        let imageUrl = res.urls[0];
        context.emit("onChangeFile", imageUrl);
        loading.value = false;
      } catch (e) {
        loading.value = false;
      }
    };
    return {
      loading,
      fileUploade,
      triggerUpload,
    };
  },
});
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  width: 130px;
  height: 130px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
</style>
